﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OVS_FormsRecognition.Manager;
using System.Windows.Controls;
using System.Net.Mail;
using System.Net;
using OVS.BusinessObjects;
using OVS.BLL;
using OVS.DAL;
using System.Net.Sockets;
using System.Windows;
using System.Threading;
using OVS_NotificationSender.EventArg;
using System.Configuration;
namespace OVS_NotificationSender.Manager
{
    public class SMSSenderManager
    {

        #region attributs
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();

        #endregion


        /// <summary>
        /// Logger par défaut du ManagerUtilisateurs
        /// </summary>
        private static readonly log4net.ILog _Log = log4net.LogManager.GetLogger(typeof(SMSSenderManager));

        #region Gestion du singleton

        /// <summary>
        /// Instance locale pour héberger le singleton
        /// </summary>
        static SMSSenderManager instance = null;

        /// <summary>
        /// Objet permettant la gestion des LOCK lors de l'instanciation
        /// </summary>
        static readonly object padlock = new object();

        /// <summary>
        /// Constructeur par défaut
        /// </summary>
        SMSSenderManager()
        {
            if (_Log.IsDebugEnabled)
                _Log.DebugFormat("Nouvelle instance de '{0}'", this.GetType().ToString());

        }

        /// <summary>
        /// Déclaration unique par gestion du singleton
        /// </summary>
        public static SMSSenderManager Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new SMSSenderManager();
                    }
                    return instance;
                }
            }
        }

        #endregion Gestion du singleton


        /// <summary>
        /// Sends the SMS in thread.
        /// </summary>
        /// <param name="pPhoneNumber">The p phone number.</param>
        /// <param name="pMessage">The p message.</param>
        public void sendSMSInThread(string pPhoneNumber, string pMessage)
        {
            Thread smsSender = new Thread(sendSMS);
            SendSMSEventArgs pSendSMSEventArgs = new SendSMSEventArgs();

            pSendSMSEventArgs.PhoneNumber = pPhoneNumber;
            pSendSMSEventArgs.Message = pMessage;
            smsSender.Start(pSendSMSEventArgs);
        }

        /// <summary>
        /// Sends the SMS.
        /// </summary>
        /// <param name="pSendSMSEventArgs">The <see cref="SendSMSEventArgs" /> instance containing the event data.</param>
        private static void sendSMS(object pSendSMSEventArgs)
        {

            SendSMSEventArgs args = pSendSMSEventArgs as SendSMSEventArgs;

            if (args == null)
                return;
            if (String.IsNullOrEmpty(args.PhoneNumber))
                return;
            if (String.IsNullOrEmpty(args.Message))
                return;

            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 11000 on the local computer.
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = IPAddress.Parse(ConfigurationManager.AppSettings["PhoneSMSSenderIp"]);
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 5001);

                // Create a TCP/IP  socket.
                Socket sender = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                        sender.RemoteEndPoint.ToString());

                    // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes(args.PhoneNumber + ";" + args.Message);

                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);

                    //// Receive the response from the remote device.
                    //int bytesRec = sender.Receive(bytes);
                    //Console.WriteLine("Echoed test = {0}",
                    //    Encoding.ASCII.GetString(bytes,0,bytesRec));

                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();

                }
                catch (ArgumentNullException ane)
                {
                   
                     _Log.WarnFormat("ArgumentNullException : {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    _Log.WarnFormat("SocketException : {0}", se.ToString());
                }
                catch (Exception e)
                {
                    _Log.ErrorFormat("Unexpected exception : {0}", e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

    }
}
